<script setup>
import { Delete, Download, Phone, Plus, Refresh, Search, Upload } from '@element-plus/icons-vue';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { ref } from 'vue'
import { onMounted } from 'vue'
import { getUserList,addUser,updateUser,deleteUser,batchDeleteUser } from '../../api/user';
import { ElMessage,ElMessageBox } from 'element-plus';

//表单数据
const formData = ref({
  id:'',
  username: '',
  password: '',
  phone: '',
  dept: '',
  status: ''
})

//表格数据
const tableData = ref([])

onMounted(() => {
  getData()
})

//获取用户数据
const getData = async () => {
  await getUserList(pagination.value).then(res => {
    tableData.value = res.data.list
    //设置分页数据
    pagination.value.total= res.data.total
  })
  .catch(error => {
      console.error(error.message)
  })
}
//分页数据模型
const pagination =ref({
  currentPage :1,
  pageSize :10,
  total:0
})

//定义表单实例
const formRef =ref(null)

//弹框标题
const title = ref('')
const dialogFormVisible = ref(false)
//弹出添加模态框
const handleAddModel = () => {
  dialogFormVisible.value = true
  title.value="新增用户"
}

//编辑用户模态框
const handelEdit=(row)=>{
  dialogFormVisible.value = true;
  title.value = "编辑用户"
  //将数据填充到表单
  formData.value = row
}
//取消按钮
const cancel = () =>{
  dialogFormVisible.value = false
  reset()
}
//重置表单
const reset=()=>{
  formData.value={
    id:'',
    username: '',
    password: '',
    phone: '',
    dept: '',
    status: ''
  }
}

//提交表单数据
const submitForm= async(row)=>{
  formRef.value.validate((vaild)=>{
    if(vaild){
     if(formData.value.id){
      //修改用户信息
      updateUser(formData.value).then(res=>{
        if(res.code==200){
          ElMessage.success(res.message)
          //关闭添加的模态框
          cancel()
          reset()
          getData()
        }else{
          ElMessage.error(res.message)

        }
      }).catch(error=>{
        ElMessage.error(error.message)
      })
     }else{
      //添加用户信息
       addUser(formData.value).then(res=>{
    if(res.code==200){
      ElMessage.success(res.message)
      //关闭添加的模态框
      cancel()
      //重新获取数据
      getData()
      //重置表单
      reset()
    }else{
      ElMessage.error(res.message)
    }
  }).catch((error)=>{
    ElMessage.error(error.message)
  })
     }
    }
  })
}

//登录
const rules = {
  username: [
    {
      required: true,
      message: '请输入账号',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 5,
      max: 15,
      message: '密码最低6位数',
    }
  ],
  dept: [
    {
      required: true,
      message: '请输入部门名称',
      trigger: 'blur'
    }
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'blur'
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号'
    }
  ]

}

//删除用户信息
const handleDelete=(id)=>{ 
  ElMessageBox.confirm(
    '此操作将永久删除该用户, 是否继续?', '提示', 
   {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(()=>{
    deleteUser(id).then((res)=>{
      ElMessage.success(res.message)
      getData()
      })
    }).catch(()=>{
      ElMesssage({
        type:'info',
        message:'取消删除'
      })
    })
  }

//文件上传成功时的函数
const handleSuccess=(res)=>{
  console.log(res)
  formData.value.photo = res.data
}

//导入excel文件成功
const importExcelSuccess = (res) => { 
  if(res.code == 200){
    ElMessage.success(res.message)
    getData()
  } else {
    ElMessage.error(res.message)
  }
}
//分页查询数据
const handleCurrentChange =(val) => {
  //设置当前页码
  pagination.value.current = val
  //重新调用查询数据的方法
  getData()
}

//文件导出
const handleExport = () => {
  window.open("http://localhost:8080/api/export")
}

// 添加选中行的引用
const selectedRows = ref([])
const multipleTableRef = ref()

// 处理选中行变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 批量删除用户信息
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条数据')
    return
  }
  
  const ids = selectedRows.value.map(row => row.id)
  
  ElMessageBox.confirm(
    `此操作将永久删除选中的 ${selectedRows.value.length} 个用户, 是否继续?`, 
    '提示', 
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    batchDeleteUser(ids).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.message)
        getData()
        // 清空选中状态
        multipleTableRef.value.clearSelection()
      } else {
        ElMessage.error(res.message)
      }
    }).catch((error) => {
      ElMessage.error(error.message)
    })
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}


</script>
<template>
  <div class="user-box">
    <!--操作栏-->
    <el-row>
      <el-col>
        <div class="grid-content ep-bg-purple">
          <el-form :inline="true">
            <el-form-item class="input-item">
              <el-input placeholder="请输入用户名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-select v-model="value" class="m-2" placeholder="请选择用户状态" style="width: 200px">
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
                <el-option />
              </el-select>
            </el-form-item>
            <el-button type="primary" :icon="Search" class="btn">搜索</el-button>
            <el-button plain type="primary" :icon="Refresh" class="btn">重置</el-button>
          </el-form>
          <div class="btn-group">
            <el-button type="primary" :icon="Plus" @click="handleAddModel">添加</el-button>
            <el-upload :action="'http://localhost:8080/api/import'" show-file-list="false" :handleSuccess="handleSuccess" class="upload-excel">
            <el-button type="success" :icon="Download">导入</el-button>

            </el-upload>
            <el-button type="info" :icon="Upload" @click="handleExport">导出</el-button>
            <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <!--数据列表部分-->
    <el-row>
      <el-col :span="24">
        <div class="grid-content ep-bg-purple-dark">
          <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" width="120" type="index" />
            <el-table-column property="username" label="用户名称" />
            <el-table-column property="phone" label="电话号码" />
            <el-table-column property="dept" label="所属部门" />
            <el-table-column property="photo" label="照片" >
            <template #default="scope">
              <div class="demo-image__preview">
              <el-image style="width: 50px; height: 50px" :src="'http://localhost:8080'+scope.row.photo" 
              :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="srcList"
              :initial-index="4" fit="cover" />
              </div>
            </template>
            </el-table-column>
            <el-table-column property="status" label="状态">
              <template #default="scope">
                <el-switch v-model="scope.row.status" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                :active-value=1 :inactive-value=0 />
              </template>
            </el-table-column>
            <el-table-column property="createDate" label="创建时间" />
            <el-table-column label="操作">
              <template #default="scope">
              <el-button type="warring" plain @click="handelEdit(scope.row)">修改</el-button>
              <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-config-provider :local="zhCn">
            <el-pagination v-model:current-page="pagination.currentPage" style="margin: 15px;" v-model:page-size="pagination.pageSize"
              :page-sizes="[100, 200, 300, 400]" :small="small" :disabled="disabled" :background="background"
              layout="total, sizes, prev, pager, next, jumper" :total=pagination.total @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </el-config-provider>
        </div>

      </el-col>
    </el-row>
    <!--添加状态框-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="600">
      <el-form ref="formRef" :model="formData" :rules="rules">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="formData.username" size="large" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" size="large" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="所属部门" prop="dept">
          <el-input v-model="formData.dept" size="large" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="登录密码" size="large" prop="password">
          <el-input v-model="formData.password" type="password" show-password-="true" placeholder="请输入登录密码" />
        </el-form-item>
        <el-form-item label="状&nbsp;&nbsp;&nbsp;态" style="margin-left: 10px;">
          <el-switch v-model="formData.status" inline-prompt active-text="启用" inactive-text="禁用" active-value=1
            inactive-value=0 />
        </el-form-item>
        <el-form-item label="用户头像">
          <el-upload v-model:file-list="fileList" action="http://localhost:8080/api/upload"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleSuccess">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
.grid-content {
  width: 100%;
  background-color: #fff;
  margin: 5px;
  padding-bottom: 10px;
}

.input-item {
  width: 200px;
  padding: 20px;
}

.el-form {
  text-align: left;
}

.el-select {
  margin-left: -30px;
}

.el-button:focus {
  outline: none;
}

.btn-group {
  text-align: left;
  display: flex;
  margin-top: -28px;
  margin-left: 20px;
}

.btn {
  margin-top: -20px;
}

:deep() .el-dialog__header {
  text-align: left;
}


:deep() .el-button:focus{
  border: none;
}

.upload-excel{
  display: inline-block;
  margin-left: 10px;
  margin-right: 10px;
}
</style>